<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件共享系统 - 颍上县耿棚中学</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 10px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .main-content {
            padding: 20px;
        }

        .upload-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border: 2px dashed #ddd;
            text-align: center;
            transition: all 0.3s ease;
        }

        .upload-section:hover {
            border-color: #4CAF50;
            background: #f0f8f0;
        }

        .upload-section.dragover {
            border-color: #4CAF50;
            background: #e8f5e8;
        }

        .file-input {
            display: none;
        }

        .upload-btn {
            background: #4CAF50;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
            margin: 10px;
        }

        .upload-btn:hover {
            background: #45a049;
            transform: translateY(-2px);
        }

        .breadcrumb-nav {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px 15px;
            margin-bottom: 15px;
            border: 1px solid #e9ecef;
            font-size: 14px;
        }

        .breadcrumb-item {
            color: #007bff;
            cursor: pointer;
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 4px;
            transition: background-color 0.2s;
        }

        .breadcrumb-item:hover {
            background-color: #e9ecef;
        }

        .breadcrumb-item:not(:last-child)::after {
            content: ' / ';
            color: #6c757d;
            margin: 0 4px;
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
        }

        .search-box {
            flex: 1;
            min-width: 200px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .file-list {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 15px;
            border-bottom: 1px solid #eee;
            transition: background 0.3s ease;
        }

        .file-item:hover {
            background: #f8f9fa;
        }

        .file-item:last-child {
            border-bottom: none;
        }

        .file-icon {
            width: 40px;
            height: 40px;
            margin-right: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            font-size: 18px;
        }

        .file-info {
            flex: 1;
            min-width: 0;
        }

        .file-name {
            font-weight: 500;
            margin-bottom: 5px;
            word-break: break-all;
        }

        .file-meta {
            font-size: 12px;
            color: #666;
        }

        .file-actions {
            display: flex;
            gap: 5px;
            flex-shrink: 0;
        }

        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        .empty-state {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #333;
            color: white;
            padding: 12px 20px;
            border-radius: 5px;
            z-index: 2000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }

        .toast.show {
            transform: translateX(0);
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        .toast.warning {
            background: #ffc107;
            color: #333;
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1500;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4CAF50;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .file-item.selected {
            background: #e3f2fd;
            border-left: 4px solid #2196F3;
        }

        .batch-actions {
            display: none;
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 10px;
            border: 1px solid #dee2e6;
        }

        .batch-actions.show {
            display: block;
        }

        .upload-status {
            margin-top: 10px;
            font-size: 14px;
            color: #666;
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #f0f0f0;
            border-radius: 2px;
            overflow: hidden;
            margin-top: 10px;
        }

        .progress-fill {
            height: 100%;
            background: #4CAF50;
            transition: width 0.3s ease;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 90%;
            max-height: 90%;
            overflow: auto;
        }

        .close {
            float: right;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }

        .close:hover {
            color: #333;
        }

        /* 移动端优化 */
        @media (max-width: 768px) {
            body {
                padding: 5px;
            }

            .container {
                margin: 0;
                border-radius: 10px;
                min-height: calc(100vh - 10px);
            }

            .header {
                padding: 15px 10px;
            }

            .header h1 {
                font-size: 18px;
                margin-bottom: 3px;
            }

            .header p {
                font-size: 12px;
            }

            .main-content {
                padding: 10px;
            }

            .upload-section {
                padding: 15px 10px;
                margin-bottom: 15px;
            }

            .upload-btn {
                padding: 10px 20px;
                font-size: 14px;
                margin: 5px;
                width: calc(50% - 10px);
                display: inline-block;
            }

            .controls {
                flex-direction: column;
                gap: 8px;
            }

            .search-box {
                width: 100%;
                padding: 12px;
                font-size: 16px; /* 防止iOS缩放 */
            }

            .btn {
                padding: 10px 16px;
                font-size: 14px;
                min-height: 44px; /* 触摸友好 */
            }

            .file-item {
                padding: 12px 10px;
                flex-direction: row;
                align-items: center;
                min-height: 60px;
            }

            .file-icon {
                width: 35px;
                height: 35px;
                margin-right: 10px;
                font-size: 16px;
            }

            .file-info {
                flex: 1;
                min-width: 0;
            }

            .file-name {
                font-size: 14px;
                line-height: 1.3;
            }

            .file-meta {
                font-size: 11px;
            }

            .file-actions {
                flex-direction: column;
                gap: 3px;
                min-width: 60px;
            }

            .action-btn {
                padding: 6px 8px;
                font-size: 11px;
                min-height: 32px;
                width: 100%;
            }

            .batch-actions {
                padding: 8px;
                flex-wrap: wrap;
                gap: 5px;
            }

            .batch-actions .btn {
                flex: 1;
                min-width: calc(50% - 5px);
                margin: 2px 0;
            }

            .toast {
                top: 10px;
                right: 10px;
                left: 10px;
                transform: translateY(-100px);
                font-size: 14px;
            }

            .toast.show {
                transform: translateY(0);
            }

            .modal-content {
                margin: 10px;
                padding: 15px;
                max-width: calc(100% - 20px);
                max-height: calc(100% - 20px);
            }
        }

        /* 小屏幕设备进一步优化 */
        @media (max-width: 480px) {
            .header h1 {
                font-size: 16px;
            }

            .upload-btn {
                width: 100%;
                margin: 3px 0;
            }

            .file-item {
                padding: 10px 8px;
            }

            .file-actions {
                min-width: 50px;
            }

            .action-btn {
                font-size: 10px;
                padding: 4px 6px;
            }

            .batch-actions .btn {
                min-width: 100%;
                margin: 2px 0;
            }
        }

        /* 触摸设备优化 */
        @media (hover: none) and (pointer: coarse) {
            .file-item:hover {
                background: inherit;
            }

            .file-item:active {
                background: #f0f0f0;
            }

            .btn:hover {
                transform: none;
            }

            .btn:active {
                transform: scale(0.98);
            }

            .upload-btn:hover {
                transform: none;
            }

            .upload-btn:active {
                transform: scale(0.98);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📁 文件共享系统</h1>
            <p>颍上县耿棚中学 - 局域网文件共享平台</p>
        </div>

        <div class="main-content">
            <!-- 上传区域 -->
            <div class="upload-section" id="uploadArea">
                <div id="uploadHint">📤 拖拽文件到此处或点击上传</div>
                <input type="file" id="fileInput" class="file-input" multiple>
                <button class="upload-btn" onclick="document.getElementById('fileInput').click()" title="快捷键: Ctrl+U">选择文件</button>
                <button class="upload-btn" onclick="createFolder()" title="快捷键: Ctrl+N">新建文件夹</button>
                <div id="uploadProgress" class="progress-bar" style="display: none;">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
            </div>

            <!-- 批量操作栏 -->
            <div class="batch-actions" id="batchActions">
                <span id="selectedCount">已选择 0 个文件</span>
                <button class="btn btn-danger" onclick="deleteSelected()">🗑️ 删除选中</button>
                <button class="btn btn-primary" onclick="downloadSelected()">📥 批量下载</button>
                <button class="btn" onclick="clearSelection()">❌ 取消选择</button>
            </div>

            <!-- 面包屑导航 -->
            <div class="breadcrumb-nav" id="breadcrumbNav">
                <span class="breadcrumb-item" onclick="navigateToFolder('')">🏠 根目录</span>
            </div>

            <!-- 控制栏 -->
            <div class="controls">
                <input type="text" class="search-box" id="searchBox" placeholder="🔍 搜索文件...">
                <button class="btn btn-primary" onclick="refreshFiles()">🔄 刷新</button>
                <button class="btn btn-success" onclick="toggleSelectAll()">✅ 全选</button>
                <button class="btn btn-danger" onclick="clearAllFiles()">🗑️ 清空目录</button>
            </div>

            <!-- 文件列表 -->
            <div class="file-list">
                <div id="fileListContent">
                    <div class="loading">📂 正在加载文件列表...</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast 通知 -->
    <div id="toast" class="toast"></div>

    <!-- 加载遮罩 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="spinner"></div>
    </div>

    <!-- 文件查看模态框 -->
    <div id="fileModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h3 id="modalTitle">文件内容</h3>
            <div id="modalContent"></div>
        </div>
    </div>

    <script>
        let allFiles = [];
        let selectedFiles = new Set();
        let isSelectAllMode = false;
        let currentDirectory = ''; // 当前目录路径
        let breadcrumbData = []; // 面包屑导航数据

        // Toast 通知系统
        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = `toast ${type}`;
            toast.classList.add('show');
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // 显示/隐藏加载遮罩
        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }

        function hideLoading() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }

        // 更新选中文件计数
        function updateSelectedCount() {
            const count = selectedFiles.size;
            document.getElementById('selectedCount').textContent = `已选择 ${count} 个文件`;
            const batchActions = document.getElementById('batchActions');
            if (count > 0) {
                batchActions.classList.add('show');
            } else {
                batchActions.classList.remove('show');
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            refreshFiles();
            setupEventListeners();
            setupKeyboardShortcuts();
        });

        // 设置键盘快捷键
        function setupKeyboardShortcuts() {
            document.addEventListener('keydown', function(e) {
                // Ctrl+U 或 Cmd+U: 上传文件
                if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
                    e.preventDefault();
                    document.getElementById('fileInput').click();
                }
                
                // Ctrl+N 或 Cmd+N: 新建文件夹
                if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                    e.preventDefault();
                    createFolder();
                }
                
                // F5: 刷新文件列表
                if (e.key === 'F5') {
                    e.preventDefault();
                    refreshFiles();
                }
                
                // Escape: 取消选择
                if (e.key === 'Escape') {
                    clearSelection();
                }
                
                // Delete: 删除选中文件
                if (e.key === 'Delete' && selectedFiles.size > 0) {
                    deleteSelected();
                }
            });
        }

        function setupEventListeners() {
            // 文件上传
            document.getElementById('fileInput').addEventListener('change', handleFileUpload);
            
            // 拖拽上传
            const uploadArea = document.getElementById('uploadArea');
            uploadArea.addEventListener('dragover', handleDragOver);
            uploadArea.addEventListener('dragleave', handleDragLeave);
            uploadArea.addEventListener('drop', handleDrop);
            
            // 搜索
            setupSearchInput();
            
            // 移动端触摸优化
            setupTouchInteractions();
            
            // 防止双击缩放
            document.addEventListener('touchstart', function(e) {
                if (e.touches.length > 1) {
                    e.preventDefault();
                }
            }, { passive: false });
            
            let lastTouchEnd = 0;
            document.addEventListener('touchend', function(e) {
                const now = (new Date()).getTime();
                if (now - lastTouchEnd <= 300) {
                    e.preventDefault();
                }
                lastTouchEnd = now;
            }, false);
        }
        
        function setupTouchInteractions() {
            // 长按选择文件
            let touchTimer = null;
            let touchStartPos = null;
            
            document.addEventListener('touchstart', function(e) {
                const fileItem = e.target.closest('.file-item');
                if (!fileItem) return;
                
                touchStartPos = { x: e.touches[0].clientX, y: e.touches[0].clientY };
                
                touchTimer = setTimeout(() => {
                    const filename = fileItem.dataset.filename;
                    if (filename) {
                        toggleFileSelection(filename);
                        // 触觉反馈（如果支持）
                        if (navigator.vibrate) {
                            navigator.vibrate(50);
                        }
                    }
                }, 500);
            }, { passive: true });
            
            document.addEventListener('touchmove', function(e) {
                if (touchTimer && touchStartPos) {
                    const touch = e.touches[0];
                    const deltaX = Math.abs(touch.clientX - touchStartPos.x);
                    const deltaY = Math.abs(touch.clientY - touchStartPos.y);
                    
                    // 如果移动距离超过阈值，取消长按
                    if (deltaX > 10 || deltaY > 10) {
                        clearTimeout(touchTimer);
                        touchTimer = null;
                    }
                }
            }, { passive: true });
            
            document.addEventListener('touchend', function(e) {
                if (touchTimer) {
                    clearTimeout(touchTimer);
                    touchTimer = null;
                }
                touchStartPos = null;
            }, { passive: true });
            
            // 滑动手势支持
            let startX = null;
            let startY = null;
            
            document.addEventListener('touchstart', function(e) {
                const fileItem = e.target.closest('.file-item');
                if (!fileItem) return;
                
                startX = e.touches[0].clientX;
                startY = e.touches[0].clientY;
            }, { passive: true });
            
            document.addEventListener('touchend', function(e) {
                if (!startX || !startY) return;
                
                const endX = e.changedTouches[0].clientX;
                const endY = e.changedTouches[0].clientY;
                
                const deltaX = endX - startX;
                const deltaY = endY - startY;
                
                // 检测水平滑动
                if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
                    const fileItem = e.target.closest('.file-item');
                    if (fileItem) {
                        const filename = fileItem.dataset.filename;
                        if (deltaX > 0) {
                            // 右滑 - 下载
                            downloadFile(filename);
                        } else {
                            // 左滑 - 删除
                            if (confirm('确定要删除这个文件吗？')) {
                                deleteFile(filename);
                            }
                        }
                    }
                }
                
                startX = null;
                startY = null;
            }, { passive: true });
        }

        function handleDragOver(e) {
            e.preventDefault();
            e.currentTarget.classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            e.currentTarget.classList.remove('dragover');
            const files = e.dataTransfer.files;
            uploadFiles(files);
        }

        function handleFileUpload(e) {
            const files = e.target.files;
            uploadFiles(files);
        }

        async function uploadFiles(files) {
            if (files.length === 0) return;

            const progressBar = document.getElementById('uploadProgress');
            const progressFill = document.getElementById('progressFill');
            const uploadArea = document.getElementById('uploadArea');
            
            progressBar.style.display = 'block';
            showLoading();
            
            let successCount = 0;
            let failCount = 0;
            
            // 添加上传状态显示
            const statusDiv = document.createElement('div');
            statusDiv.className = 'upload-status';
            statusDiv.id = 'uploadStatus';
            uploadArea.appendChild(statusDiv);

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const formData = new FormData();
                formData.append('file', file);
                
                // 如果在子目录中，添加目录参数
                if (currentDirectory) {
                    formData.append('folder', currentDirectory);
                }
                
                // 更新状态
                statusDiv.textContent = `正在上传: ${file.name} (${i + 1}/${files.length})`;

                try {
                    // 为大文件上传设置更长的超时时间
                    const controller = new AbortController();
                    const timeoutId = setTimeout(() => controller.abort(), 300000); // 5分钟超时
                    
                    const response = await fetch('/api/upload', {
                        method: 'POST',
                        body: formData,
                        signal: controller.signal
                    });
                    
                    clearTimeout(timeoutId);

                    const result = await response.json();
                    if (result.success) {
                        successCount++;
                        showToast(`${file.name} 上传成功`, 'success');
                    } else {
                        failCount++;
                        showToast(`${file.name} 上传失败: ${result.error}`, 'error');
                    }
                } catch (error) {
                    failCount++;
                    showToast(`${file.name} 上传失败: ${error.message}`, 'error');
                }

                // 更新进度
                const progress = ((i + 1) / files.length) * 100;
                progressFill.style.width = progress + '%';
            }

            // 显示最终结果
            const totalMessage = `上传完成！成功: ${successCount}, 失败: ${failCount}`;
            if (failCount === 0) {
                showToast(totalMessage, 'success');
            } else if (successCount === 0) {
                showToast(totalMessage, 'error');
            } else {
                showToast(totalMessage, 'warning');
            }

            // 隐藏进度条并刷新文件列表
            setTimeout(() => {
                progressBar.style.display = 'none';
                progressFill.style.width = '0%';
                hideLoading();
                if (statusDiv) statusDiv.remove();
                refreshFiles();
            }, 1000);

            // 清空文件输入
            document.getElementById('fileInput').value = '';
        }

        async function refreshFiles(directory = currentDirectory) {
            showLoading();
            try {
                const url = directory ? `/api/files?dir=${encodeURIComponent(directory)}` : '/api/files';
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.success) {
                    // 合并文件夹和文件数据
                    const folders = (result.folders || []).map(folder => ({
                        ...folder,
                        is_directory: true
                    }));
                    const files = result.files || [];
                    allFiles = [...folders, ...files];
                    
                    breadcrumbData = result.breadcrumb || [];
                    currentDirectory = directory;
                    
                    displayFiles(allFiles);
                    updateBreadcrumb();
                    showToast('文件列表已刷新', 'success');
                } else {
                    document.getElementById('fileListContent').innerHTML = 
                        `<div class="empty-state">❌ 加载失败: ${result.error}</div>`;
                    showToast('获取文件列表失败: ' + result.error, 'error');
                }
            } catch (error) {
                document.getElementById('fileListContent').innerHTML = 
                    `<div class="empty-state">❌ 网络错误: ${error.message}</div>`;
                showToast('获取文件列表失败: ' + error.message, 'error');
            } finally {
                hideLoading();
            }
        }

        // 更新面包屑导航
        function updateBreadcrumb() {
            const breadcrumbNav = document.getElementById('breadcrumbNav');
            let breadcrumbHtml = '<span class="breadcrumb-item" onclick="navigateToFolder(\'\')" title="返回根目录">🏠 根目录</span>';
            
            if (breadcrumbData && breadcrumbData.length > 0) {
                breadcrumbData.forEach(item => {
                    breadcrumbHtml += `<span class="breadcrumb-item" onclick="navigateToFolder('${item.path}')" title="进入 ${item.name}">${item.name}</span>`;
                });
            }
            
            breadcrumbNav.innerHTML = breadcrumbHtml;
            
            // 更新上传提示文本
            const uploadHint = document.getElementById('uploadHint');
            if (currentDirectory) {
                const currentFolderName = breadcrumbData.length > 0 ? breadcrumbData[breadcrumbData.length - 1].name : currentDirectory;
                uploadHint.textContent = `📤 拖拽文件到 "${currentFolderName}" 文件夹或点击上传`;
            } else {
                uploadHint.textContent = '📤 拖拽文件到此处或点击上传';
            }
        }

        // 导航到指定文件夹
        async function navigateToFolder(folderPath) {
            await refreshFiles(folderPath);
        }

        function displayFiles(files) {
            const container = document.getElementById('fileListContent');
            
            if (files.length === 0) {
                container.innerHTML = '<div class="empty-state">📂 暂无文件，请上传文件</div>';
                selectedFiles.clear();
                updateSelectedCount();
                return;
            }

            container.innerHTML = files.map(file => {
                const icon = file.is_directory ? '📁' : getFileIcon(file.type);
                const size = file.is_directory ? '文件夹' : formatFileSize(file.size);
                const date = new Date(file.modified).toLocaleString('zh-CN');
                // 使用系统文件名作为选择标识，但显示原始文件名
                const systemPath = file.system_filename ? (currentDirectory ? `${currentDirectory}/${file.system_filename}` : file.system_filename) : file.path;
                const isSelected = selectedFiles.has(systemPath);
                
                const clickAction = file.is_directory ? 
                    `navigateToFolder('${file.path}')` : 
                    `toggleFileSelection('${systemPath}')`;
                
                return `
                    <div class="file-item ${isSelected ? 'selected' : ''}" data-filename="${systemPath}" data-original-name="${file.name}" onclick="${clickAction}">
                        <div class="file-icon" style="background: ${file.is_directory ? '#ffc107' : getFileColor(file.type)}">
                            ${icon}
                        </div>
                        <div class="file-info">
                            <div class="file-name">${file.name}</div>
                            <div class="file-meta">${size} • ${date}</div>
                        </div>
                        <div class="file-actions" onclick="event.stopPropagation()">
                            ${file.is_directory ? 
                                `<button class="action-btn btn-primary" onclick="navigateToFolder('${file.path}')">📂 打开</button>
                                 <button class="action-btn btn-danger" onclick="deleteFile('${file.path}')">🗑️ 删除</button>` :
                                `<button class="action-btn btn-primary" onclick="downloadFile('${systemPath}')">📥 下载</button>
                                 <button class="action-btn btn-success" onclick="viewFile('${systemPath}')">👁️ 查看</button>
                                 <button class="action-btn btn-danger" onclick="deleteFile('${systemPath}')">🗑️ 删除</button>`
                            }
                        </div>
                    </div>
                `;
            }).join('');
            updateSelectedCount();
        }

        function getFileIcon(type) {
            if (!type) return '📄';
            if (type.startsWith('image/')) return '🖼️';
            if (type.startsWith('video/')) return '🎥';
            if (type.startsWith('audio/')) return '🎵';
            if (type.includes('pdf')) return '📕';
            if (type.includes('word')) return '📘';
            if (type.includes('excel')) return '📗';
            if (type.includes('powerpoint')) return '📙';
            if (type.includes('zip') || type.includes('rar')) return '📦';
            if (type.startsWith('text/')) return '📝';
            return '📄';
        }

        function getFileColor(type) {
            if (!type) return '#6c757d';
            if (type.startsWith('image/')) return '#e74c3c';
            if (type.startsWith('video/')) return '#9b59b6';
            if (type.startsWith('audio/')) return '#f39c12';
            if (type.includes('pdf')) return '#e74c3c';
            if (type.includes('word')) return '#3498db';
            if (type.includes('excel')) return '#27ae60';
            if (type.includes('powerpoint')) return '#e67e22';
            if (type.includes('zip') || type.includes('rar')) return '#95a5a6';
            if (type.startsWith('text/')) return '#2ecc71';
            return '#6c757d';
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function filterFiles() {
            const searchTerm = document.getElementById('searchBox').value.toLowerCase().trim();
            if (searchTerm === '') {
                displayFiles(allFiles);
                showToast('已显示所有文件', 'success');
            } else {
                const filteredFiles = allFiles.filter(file => {
                    // 搜索原始文件名和系统文件名
                    const fileName = (file.name || file.path || '').toLowerCase();
                    const systemFileName = (file.system_filename || '').toLowerCase();
                    return fileName.includes(searchTerm) || systemFileName.includes(searchTerm);
                });
                
                displayFiles(filteredFiles);
                
                if (filteredFiles.length === 0) {
                    showToast(`未找到包含 "${searchTerm}" 的文件`, 'warning');
                } else {
                    showToast(`找到 ${filteredFiles.length} 个匹配文件`, 'success');
                }
            }
            
            // 清空选择
            selectedFiles.clear();
            updateSelectedCount();
        }
        
        // 实时搜索
        function setupSearchInput() {
            const searchInput = document.getElementById('searchBox');
            let searchTimeout;
            
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    filterFiles();
                }, 300); // 300ms 延迟，避免频繁搜索
            });
            
            // 回车键搜索
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    clearTimeout(searchTimeout);
                    filterFiles();
                }
            });
        }

        function downloadFile(path) {
            window.open(`/api/download/${encodeURIComponent(path)}`, '_blank');
        }

        async function viewFile(path) {
            try {
                const response = await fetch(`/api/file/${encodeURIComponent(path)}`);
                const result = await response.json();
                
                if (result.success) {
                    const modal = document.getElementById('fileModal');
                    const title = document.getElementById('modalTitle');
                    const content = document.getElementById('modalContent');
                    
                    title.textContent = path;
                    
                    if (result.type === 'text') {
                        content.innerHTML = `<pre style="white-space: pre-wrap; max-height: 400px; overflow: auto;">${result.content}</pre>`;
                    } else {
                        content.innerHTML = `<p>${result.message}</p>`;
                    }
                    
                    modal.style.display = 'block';
                } else {
                    alert(`查看失败: ${result.error}`);
                }
            } catch (error) {
                alert(`查看失败: ${error.message}`);
            }
        }

        // 文件选择功能
        function toggleFileSelection(filename) {
            if (selectedFiles.has(filename)) {
                selectedFiles.delete(filename);
            } else {
                selectedFiles.add(filename);
            }
            
            // 更新界面
            const fileItem = document.querySelector(`[data-filename="${filename}"]`);
            if (fileItem) {
                const checkbox = fileItem.querySelector('input[type="checkbox"]');
                if (selectedFiles.has(filename)) {
                    fileItem.classList.add('selected');
                    if (checkbox) checkbox.checked = true;
                } else {
                    fileItem.classList.remove('selected');
                    if (checkbox) checkbox.checked = false;
                }
            }
            
            updateSelectedCount();
        }

        function toggleSelectAll() {
            if (isSelectAllMode) {
                // 取消全选
                selectedFiles.clear();
                isSelectAllMode = false;
            } else {
                // 全选
                allFiles.forEach(file => {
                    selectedFiles.add(file.path);
                });
                isSelectAllMode = true;
            }
            displayFiles(allFiles);
        }

        function clearSelection() {
            selectedFiles.clear();
            isSelectAllMode = false;
            displayFiles(allFiles);
        }

        async function deleteSelected() {
            if (selectedFiles.size === 0) {
                showToast('请先选择要删除的文件', 'warning');
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedFiles.size} 个文件吗？`)) {
                return;
            }

            showLoading();
            let successCount = 0;
            let failCount = 0;

            for (const filename of selectedFiles) {
                try {
                    const response = await fetch(`/api/delete/${encodeURIComponent(filename)}`, {
                        method: 'DELETE'
                    });
                    const result = await response.json();
                    if (result.success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (error) {
                    failCount++;
                }
            }

            hideLoading();
            selectedFiles.clear();
            
            const message = `删除完成！成功: ${successCount}, 失败: ${failCount}`;
            if (failCount === 0) {
                showToast(message, 'success');
            } else {
                showToast(message, 'warning');
            }
            
            refreshFiles();
        }

        function downloadSelected() {
            if (selectedFiles.size === 0) {
                showToast('请先选择要下载的文件', 'warning');
                return;
            }

            selectedFiles.forEach(filename => {
                downloadFile(filename);
            });
            
            showToast(`开始下载 ${selectedFiles.size} 个文件`, 'success');
        }

        async function deleteFile(path) {
            if (!confirm(`确定要删除文件 "${path}" 吗？`)) return;
            
            showLoading();
            try {
                const response = await fetch(`/api/delete/${encodeURIComponent(path)}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                if (result.success) {
                    showToast('删除成功', 'success');
                    selectedFiles.delete(path);
                    refreshFiles();
                } else {
                    showToast(`删除失败: ${result.error}`, 'error');
                }
            } catch (error) {
                showToast(`删除失败: ${error.message}`, 'error');
            } finally {
                hideLoading();
            }
        }

        async function createFolder() {
            const folderName = prompt('请输入文件夹名称:');
            if (!folderName || !folderName.trim()) return;
            
            const trimmedName = folderName.trim();
            
            // 验证文件夹名称
            if (!/^[^<>:"/\\|?*]+$/.test(trimmedName)) {
                showToast('文件夹名称包含非法字符', 'error');
                return;
            }
            
            showLoading();
            try {
                const requestBody = { name: trimmedName };
                
                // 如果在子目录中，添加父目录参数
                if (currentDirectory) {
                    requestBody.parent_dir = currentDirectory;
                }
                
                const response = await fetch('/api/create_folder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });
                
                const result = await response.json();
                hideLoading();
                if (result.success) {
                    showToast('文件夹创建成功', 'success');
                    refreshFiles();
                } else {
                    showToast('创建失败: ' + result.error, 'error');
                }
            } catch (error) {
                hideLoading();
                showToast('创建失败: ' + error.message, 'error');
            }
        }

        async function clearAllFiles() {
            if (!confirm('确定要清空整个目录吗？此操作不可恢复！')) {
                return;
            }

            if (allFiles.length === 0) {
                showToast('目录已经是空的', 'warning');
                return;
            }

            showLoading();
            let successCount = 0;
            let failCount = 0;

            for (const file of allFiles) {
                try {
                    const response = await fetch(`/api/delete/${encodeURIComponent(file.path)}`, {
                        method: 'DELETE'
                    });
                    const result = await response.json();
                    if (result.success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (error) {
                    failCount++;
                }
            }

            hideLoading();
            selectedFiles.clear();
            
            const message = `清空完成！成功: ${successCount}, 失败: ${failCount}`;
            if (failCount === 0) {
                showToast(message, 'success');
            } else {
                showToast(message, 'warning');
            }
            
            refreshFiles();
        }

        function closeModal() {
            document.getElementById('fileModal').style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('fileModal');
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        }
    </script>
</body>
</html>